import 'dart:io';

import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/poster_create_info_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/edit_poster_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/select_address_list_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/widgets/poster_feedback_dialog.dart';
import 'package:e_reception_flutter/media_library/media_library_index/widgets/share_poster_menu_dialog.dart';
import 'package:e_reception_flutter/singleton/share_repository/share_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/color_constants.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/widgets/bubble_widget.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/widgets/operation_success_tips_dialog.dart';
import 'package:e_reception_flutter/utils/file_utils.dart';
import 'package:e_reception_flutter/utils/lunar_utils.dart';
// import 'package:e_reception_flutter/utils/lunar_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:sharesdk_plugin/sharesdk_defines.dart';
import 'package:sharesdk_plugin/sharesdk_map.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_save_util_lib.dart';
import 'package:vg_base/vg_screen_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../media_library_index_view_model.dart';

class PosterDetailPage extends StatefulWidget {
  static const ROUTER = "PortDetailPage";

  final String url;
  final String hsn;
  final String id;
  final String likeflg;
  //是否显示logo 00显示 01不显示
  final String logoflg;
  //是否显示地址 00显示 01不显示
  final String addressflg;
  //diy参数
  final String addressdiy;
  final String namediy;
  final String logodiy;

  //00:什么都没有 01:logo 02:名称 03:地址 04:logo+名称 05:logo+地址 06:名称+地址 07:全部都有
  final String cretype;
  //diyflg 00不可diy 01diy
  final String diyflg;
  final String intoflg;
  //每日一签拼接的图地址
  final String splpicurl;
  final String position;
  final String cbid;

  final bool showSelectAddress;
  final String pictype;//09合成海报
  final String gps;//定位

  const PosterDetailPage(
      {Key key,
        @required this.url,
        this.id,
        this.likeflg,
        this.cretype,
        this.hsn,
        this.showSelectAddress,
        this.logoflg,
        this.addressflg,
        this.diyflg,
        this.intoflg,
        this.addressdiy,
        this.namediy,
        this.logodiy,
        this.splpicurl,
        this.position,
        this.cbid,
        this.pictype,
        this.gps
      })
      : assert(url != null, "currentItem must be not null");

  @override
  State<StatefulWidget> createState() => _PorterDetailState();

  static Future<dynamic> navigatorPush(
      BuildContext context,
      String url,
      String id,
      String likeflg,
      String cretype,
      String hsn,
      bool showSelectAddress,
      String logoflg,
      String addressflg,
      String diyflg,
      String intoflg,
      String addressdiy,
      String namediy,
      String logodiy,
      String splpicurl,
      String pictype,
      {String position, String cbid, String gps}
      ) {
    return RouterUtils.routeForFutureResult(
        context,
        PosterDetailPage(
          url: url,
          id: id,
          hsn: hsn,
          likeflg: likeflg,
          cretype: cretype,
          showSelectAddress: showSelectAddress,
          logoflg: logoflg,
          addressflg: addressflg,
          diyflg: diyflg,
          intoflg: intoflg,
          addressdiy: addressdiy,
          namediy: namediy,
          logodiy: logodiy,
          splpicurl: splpicurl,
          position: position,
          cbid: cbid,
          pictype: pictype,
          gps: gps,
        ),
        routeName: PosterDetailPage.ROUTER);
  }
}

class _PorterDetailState extends BaseState<PosterDetailPage> {
  MediaLibraryIndexViewModel _viewModel;
  WebViewController _webViewController;
  String _flag;
  String _downloadOrShare = "00"; //00下载，01分享, 02查看大图
  String _shareFlag = "00"; //00朋友圈 01好友
  List<AddressItemBean> _addressList = new List();
  String _selectAddress;
  String _cbid;
  CompanyAndAddressBean _companyAndAddressBean;

  //海报是否需要显示地址
  bool _needChangeAddress = true;

  //webview加载成功
  bool isUrlLoadComplete = false;
  bool showBubble = false;
  bool _showLogo = true;
  bool _showAddress = true;
  //00啥都不显示 01都显示，02logo, 03logo+地址, 04logo+切换,
  String _bubbleFlag = "00";
  String _cretype;
  int _bubbleHeight = 135;
  String _loadUrl;
  //是否拼接地址 00拼接 01不拼接
  bool _posterSplicing = true;
  @override
  void initState() {
    super.initState();
    // _webViewController?.loadUrl(getUrl(widget?.url));
    // loading(true, msg: "生成中");
    _cretype = widget?.cretype;
    MediaLibraryIndexViewModel.EMPTY_FLAG = false;
    _viewModel = MediaLibraryIndexViewModel(this);
    _viewModel.getCompanyAndAddressInfoWithCache(widget?.gps);
    _showLogo = ("00" == (widget?.logoflg??""));
    _showAddress = ("00" == (widget?.addressflg??""));
    _flag = widget?.likeflg ?? "";
    _cbid = widget?.cbid;
    //00:什么都没有 01:logo 02:名称 03:地址 04:logo+名称 05:logo+地址 06:名称+地址 07:全部都有
    // isHideRightWidget: !(widget?.showSelectAddress ?? false) || !_needAddress,
    if (StringUtils.isNotEmpty(_cretype ?? "")) {
      if ("00" == widget?.cretype ||
          "01" == widget?.cretype ||
          "02" == widget?.cretype ||
          "04" == widget?.cretype) {
        //不需要切换地址
        _needChangeAddress = false;
      } else {
        if(widget?.showSelectAddress ?? false){
          _needChangeAddress = true;
        }else{
          _needChangeAddress = false;
        }
      }
      //_cretype 00:什么都没有 01:logo 02:名称 03:地址 04:logo+名称 05:logo+地址 06:名称+地址 07:全部都有
      //_bubbleFlag 00啥都不显示 01都显示，02logo, 03logo+地址,
      if("00" == _cretype){
        _bubbleFlag = "00";
        _bubbleHeight = 0;
      }else if("01" == _cretype){
        _bubbleFlag = "02";
        _bubbleHeight = 45;
      }else if("02" == _cretype){
        //02只有名称的时候也不显示又上角操作按钮
        _bubbleFlag = "00";
        _bubbleHeight = 0;
      }else if("03" == _cretype || "05" == _cretype || "06" == _cretype || "07" == _cretype){
        //03 海报有地址，判断是否需要显示切换地址，需要的话，就都显示，不需要就只显示logo+地址
        //05 海报有logo+地址，
        if(_needChangeAddress){
          _bubbleFlag = "01";
          _bubbleHeight = 135;
        }else{
          _bubbleFlag = "03";
          _bubbleHeight = 90;
        }
      }else if("04" == _cretype){
        //海报有logo跟名称，那么不要地址以及切换地址，所以只显示logo
        _bubbleFlag = "02";
        _bubbleHeight = 45;
      }
    }
    _viewModel.posterLook(widget?.id, widget?.intoflg);
  }

  @override
  Widget build(BuildContext context) {
    if(_bubbleFlag == "01"){
      //如果拼接海报，按照原来的规则，都展示
      if(_posterSplicing){
        _bubbleFlag = "01";
        _bubbleHeight = 135;
      }else{
        //不拼接海报，则只展示logo
        _bubbleFlag = "02";
        _bubbleHeight = 45;
      }
    }else if(_bubbleFlag == "03"){
      //如果拼接海报，按照原来的规则，都展示
      if(_posterSplicing){
        _bubbleFlag = "03";
        _bubbleHeight = 90;
      }else{
        //不拼接海报，则只展示logo
        _bubbleFlag = "02";
        _bubbleHeight = 45;
      }
    }
    return Scaffold(
      backgroundColor: ColorConstants.BG_OR_SPLIT_COLOR,
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          Column(
              children:[
                _toTopBarWidget(),
                Expanded(
                    child: GestureDetector(
                      onTapDown: (details){
                        setState(() {
                          showBubble = false;
                        });
                      },
                      onTapUp: (details){
                        setState(() {
                          showBubble = false;
                        });
                      },
                      onTapCancel: (){
                        setState(() {
                          showBubble = false;
                        });
                      },
                      onPanDown: (details){
                        setState(() {
                          showBubble = false;
                        });
                      },
                      child: _toPlaceHolderWidget(),
                    )
                ),
              ]),
          Visibility(
            visible: showBubble,
            child: Positioned(
              top: 0,
              bottom: 0,
              left: 0,
              right: 0,
              child: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: (){
                  setState(() {
                    showBubble = !showBubble;
                  });
                },
                child: Container(
                  color: Colors.transparent,
                  child: Stack(
                    children: [
                      Positioned(
                          top: ScreenUtils.getStatusBarH(context) + 44 - 6,
                          right: 15,
                          child: BubbleWidget(
                              140.0,
                              21.0+_bubbleHeight,
                              ThemeRepository.getInstance().getLineColor_3A3F50(),
                              BubbleArrowDirection.top,
                              arrAngle: 85.0,
                              length: 104.0,
                              radius: 12.0,
                              arrHeight: 6.0,
                              strokeWidth: 0.0,
                              child: Column(
                                children: [
                                  _toToggleLogoWidget(),
                                  _toToggleAddressWidget(),
                                  _toChangAddressWidget(),
                                ],
                              )
                          )
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  ///显示logpo
  Widget _toToggleLogoWidget(){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        setState(() {
          _toggleLogo(_showLogo?"02":"01");
          _showLogo = !_showLogo;
        });
      },
      child: Container(
        height: 45,
        padding: EdgeInsets.symmetric(horizontal: 9),
        alignment: Alignment.center,
        child: Row(
          children: [
            Text(
              "显示logo",
              style: TextStyle(
                  color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                  fontSize: 14,
                  height: 1.2
              ),
            ),
            Spacer(),
            Image.asset(
              _showLogo
                  ? "images/icon_open.png"
                  :"images/icon_close.png",
              width: 36,
            ),
          ],
        ),
      ),
    );
  }

  ///显示地址
  Widget _toToggleAddressWidget(){
    //00啥都不显示 01都显示，02logo, 03logo+地址,
    return Visibility(
      visible: (("01" == _bubbleFlag) || ("03" == _bubbleFlag)) && _posterSplicing,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: (){
          setState(() {
            _toggleAddress(_showAddress?"02":"01");
            _showAddress = !_showAddress;
          });
        },
        child: Container(
          height: 45,
          padding: EdgeInsets.symmetric(horizontal: 9),
          alignment: Alignment.center,
          child: Row(
            children: [
              Text(
                "显示地址",
                style: TextStyle(
                    color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                    fontSize: 14,
                    height: 1.2
                ),
              ),
              Spacer(),
              Image.asset(
                _showAddress
                    ? "images/icon_open.png"
                    :"images/icon_close.png",
                width: 36,
              ),
            ],
          ),
        ),
      ),
    );
  }

  ///切换地址
  Widget _toChangAddressWidget(){
    //00啥都不显示 01都显示，02logo, 03logo+地址,
    return Visibility(
      visible: "01" == _bubbleFlag && _posterSplicing,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () async {
          setState(() {
            showBubble = false;
          });
          AddressItemBean addressBean = await SelectAddressListPage.navigatorPush(
              context, _addressList, _cbid, widget?.gps);
          if (StringUtils.isNotEmpty(addressBean?.branchname) && StringUtils.isNotEmpty(addressBean?.cbid)) {
            _selectAddress = addressBean?.branchname;
            _cbid = addressBean?.cbid;
            _loadUrl = getUrl(
                widget?.url, _companyAndAddressBean,
                currentAddress: _selectAddress);
            _webViewController?.loadUrl(_loadUrl);
          }
        },
        child: Container(
          height: 45,
          padding: EdgeInsets.symmetric(horizontal: 9),
          alignment: Alignment.center,
          child: Row(
            children: [
              Text(
                "切换地址",
                style: TextStyle(
                    color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                    fontSize: 14,
                    height: 1.2
                ),
              ),
              Spacer(),
              Image.asset(
                "images/index_arrow_ico.png",
                width: 6,
                height: 11,
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
        isShowBack: true,
        title: "AI海报推送",
        rightPadding: 15,
        isHideRightWidget: "00" == _bubbleFlag,
        rightWidget: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            setState(() {
              showBubble = !showBubble;
            });
          },
          child: Container(
            width: 120,
            height: 44,
            alignment: Alignment.centerRight,
            child: Image.asset(
              "images/icon_more_operations.png",
              width: 20,
            ),
          ),
        )
      // GestureDetector(
      //     onTap: () async {
      //       String address = await SelectAddressListPage.navigatorPush(
      //           context, _addressList, _selectAddress);
      //       if (StringUtils.isNotEmpty(address)) {
      //         _selectAddress = address;
      //         _webViewController?.loadUrl(getUrl(
      //             widget?.url, _companyAndAddressBean,
      //             currentAddress: _selectAddress));
      //       }
      //     },
      //     child: ValueListenableBuilder(
      //         valueListenable: _viewModel?.companyInfoNotifier,
      //         builder: (BuildContext context,
      //             CompanyAndAddressBean companyAndAddressBean, Widget child) {
      //           return ((companyAndAddressBean?.addressList?.length ?? 0) > 1)
      //               ? Text(
      //                   "切换地址",
      //                   style: TextStyle(
      //                     color: ThemeRepository.getInstance()
      //                         .getPrimaryColor_1890FF(),
      //                     fontSize: 14,
      //                   ),
      //                 )
      //               : Container();
      //         })),
    );
  }



  ///加载中
  Widget _toPlaceHolderWidget() {
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            loadingCustomWidget: Container(
              padding: EdgeInsets.only(
                  bottom: 50 + ScreenUtils.getBottomBarH(context) + 15),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  CircularProgressIndicator(
                    strokeWidth: 2,
                    // valueColor:ColorTween(begin: Colors.white, end: Colors.red[900]).animate(null),
                    // backgroundColor:(topInfo?.PVCnt?.punchcnt ?? 0)==0? Colors.transparent: Colors.white,
                    // value: _value/190,
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Text(
                    "正在加载",
                    style: TextStyle(
                        color: ThemeRepository.getInstance()
                            .getTextBFC2CC_BFC2CC(),
                        fontSize: 10),
                  )
                ],
              ),
            ),
            errorStatus: value == PlaceHolderStatusType.error,
            errorOnClick: () => _viewModel.getCompanyAndAddressInfo(widget?.gps),
            loadingOnClick: () => _viewModel.getCompanyAndAddressInfo(widget?.gps),
            child: child,
          );
        },
        child: _toInfoWidget());
  }

  ///内容布局
  Widget _toInfoWidget() {
    return ValueListenableBuilder(
        valueListenable: _viewModel?.companyInfoNotifier,
        builder: (BuildContext context,
            CompanyAndAddressBean companyAndAddressBean, Widget child) {
          _companyAndAddressBean = companyAndAddressBean;
          if(_companyAndAddressBean != null
              && _companyAndAddressBean.comCompany != null
          && ((_companyAndAddressBean.comCompany.splicing??"") == "01")){
            _posterSplicing = false;
          }
          _addressList.clear();
          if (!StringUtils.isEmpty(
              companyAndAddressBean?.comCompany?.address ?? "") && StringUtils.isEmpty(widget?.gps??"")) {
            AddressItemBean itemBean = new AddressItemBean();
            itemBean.address = companyAndAddressBean?.comCompany?.address ?? "";
            _addressList.add(itemBean);
            if(StringUtils.isEmpty(_selectAddress)){
              _selectAddress = companyAndAddressBean?.comCompany?.address ?? "";
            }
          } else {
            if (companyAndAddressBean?.addressList != null &&
                companyAndAddressBean.addressList.length > 0) {
              if (StringUtils.isNotEmpty(
                  companyAndAddressBean.addressList[0].address)) {
                if(StringUtils.isEmpty(_selectAddress)){
                  _selectAddress = companyAndAddressBean.addressList[0].branchname;
                }
              }
            }
          }
          _addressList.addAll(companyAndAddressBean?.addressList ?? []);
          return Column(
            children: [
              _toWebViewWidget(companyAndAddressBean),
              Expanded(
                child: _toBottomWidget(),
              ),
            ],
          );
        });
  }

  Widget _toWebViewWidget(CompanyAndAddressBean companyAndAddressBean) {
    double maxHeight = ScreenUtils.screenH(context) -
        ScreenUtils.getStatusBarH(context) -
        ScreenUtils.getBottomBarH(context) -
        15 -
        50 -
        44;
    double screenWidth = ScreenUtils.screenW(context) - 30;
    double width;
    double height;
    if (maxHeight / screenWidth <= 16 / 9) {
      width = maxHeight / (16 / 9);
      height = maxHeight;
    } else {
      width = screenWidth;
      height = screenWidth * (16 / 9);
    }
    print("屏幕宽： ${screenWidth}");
    print("屏幕高： ${maxHeight}");
    print("真实宽： ${width}");
    print("真实高： ${height}");
    _loadUrl = getUrl(widget.url, companyAndAddressBean, currentAddress: widget?.position??"");
    print("url:$_loadUrl");
    return Container(
      width: width,
      height: height,
      color: ColorConstants.BG_OR_SPLIT_COLOR,
      child: ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(4)),
        child: Stack(
          children: [
            Opacity(
              opacity: isUrlLoadComplete ? 1 : 0,
              child: WebView(
                initialUrl: _loadUrl,
                javascriptMode: JavascriptMode.unrestricted,
                javascriptChannels: <JavascriptChannel>[
                  _alertJavascriptChannel(context),
                  _clickJavascriptChannel(context),
                  _downloadJavascriptChannel(context),
                ].toSet(),
                onPageFinished: (String url) {
                  print("加载完成\n" + url);

                  // setState(() {
                  //   _isLoading = false;
                  //   setState(() {
                  //
                  //   });
                  // });
                },
                onWebViewCreated: (controller) {
                  _webViewController = controller;
                },
                // gestureRecognizers: Set()
                //   ..add(
                //     Factory<TapGestureRecognizer>(
                //           () => tapGestureRecognizer,
                //     ),
                //   ),
              ),
            ),
            Center(
              child: Visibility(
                visible: !isUrlLoadComplete,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    CircularProgressIndicator(
                      strokeWidth: 2,
                      // valueColor:ColorTween(begin: Colors.white, end: Colors.red[900]).animate(null),
                      // backgroundColor:(topInfo?.PVCnt?.punchcnt ?? 0)==0? Colors.transparent: Colors.white,
                      // value: _value/190,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      "正在加载",
                      style: TextStyle(
                          color: ThemeRepository.getInstance()
                              .getTextBFC2CC_BFC2CC(),
                          fontSize: 10),
                    )
                  ],
                ),
              ),
            ),
            Positioned(
              right: 0,
              bottom: 20,
              child: Visibility(
                visible: StringUtils.isEmpty(_flag),
                child: Column(
                  children: [_toLikeWidget(), _toUnLikeWidget()],
                ),
              ),
            ),
            Positioned(
              right: 12,
              bottom: 12,
              child: Visibility(
                visible: StringUtils.isNotEmpty(_flag),
                child: Container(
                  alignment: Alignment.center,
                  height: 26,
                  padding: EdgeInsets.symmetric(horizontal: 12),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(13),
                    color: Color(0x4D000000),
                  ),
                  child: Row(
                    children: [
                      Image.asset(
                        ("01" == _flag)
                            ? "images/icon_like_status.png"
                            : "images/icon_un_like_status.png",
                        height: 16,
                        width: 16,
                      ),
                      SizedBox(
                        width: 4,
                      ),
                      Text(
                        ("01" == _flag) ? "已标为喜欢" : "已标为不喜欢",
                        style: TextStyle(
                            color: Colors.white, fontSize: 12, height: 1.2),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///喜欢布局
  Widget _toLikeWidget() {
    return GestureDetector(
      onTap: () async {
        OperationSuccessTipsDialog.navigatorPushDialog(context,
            title: "谢谢您的鼓励，我们会继续努力~");
        _viewModel.likeUnLikePoster(context, widget?.hsn, widget?.id,
            (widget?.showSelectAddress ?? false) ? "02" : "01", "01");
        setState(() {
          _flag = "01";
        });
      },
      child: Image.asset(
        "images/icon_like_poster.png",
        height: 80,
        width: 80,
      ),
    );
  }

  ///不喜欢布局
  Widget _toUnLikeWidget() {
    return GestureDetector(
      onTap: () async {
        bool result = await PosterFeedbackDialog.navigatorPushDialog(
          context,
          content: "感谢您的评价反馈，是否继续在大屏机显示该文件？",
          cancelText: "返回",
          confirmText: "删除",
          confirmBgColor:
          ThemeRepository.getInstance().getMinorRedColor_F95355(),
        );
        if (result ?? false) {
          if("09" == (widget?.pictype??"")){
            //合成海报删除
            //先走不喜欢
            _viewModel.likeUnLikePoster(context, widget?.hsn, widget?.id,
                (widget?.showSelectAddress ?? false) ? "02" : "01", "02");
            //再走删除
            _viewModel.deleteComposePoster(context, widget?.hsn, widget?.id,
                (widget?.showSelectAddress ?? false) ? "02" : "01", widget?.splpicurl);
          }else{
            _viewModel.likeUnLikePoster(context, widget?.hsn, widget?.id,
                (widget?.showSelectAddress ?? false) ? "02" : "01", "03");
          }
        } else {
          _viewModel.likeUnLikePoster(context, widget?.hsn, widget?.id,
              (widget?.showSelectAddress ?? false) ? "02" : "01", "02");
        }
        setState(() {
          _flag = "02";
        });
      },
      child: Image.asset(
        "images/icon_un_like_poster.png",
        height: 80,
        width: 80,
      ),
    );
  }

  ///底部确认栏
  Widget _toBottomWidget() {
    double bottomH = ScreenUtils.getBottomBarH(context);
    return Column(
      children: [
        Expanded(
          child: Container(
            color: ColorConstants.BG_OR_SPLIT_COLOR,
          ),
        ),
        Container(
          color: Color(0xFF21263C),
          height: 50,
          child: Row(children: [
            _toCommonWidget("下载", "icon_download_poster", _download),
            Container(
              height: 24,
              width: 1,
              color: Color(0x1AFFFFFF),
            ),
            Visibility(
                visible: "01" == (widget?.diyflg??""),
                child: _toCommonWidget("编辑", "icon_edit_poster", _edit)
            ),
            Visibility(
              visible: "01" == (widget?.diyflg??""),
              child: Container(
                height: 24,
                width: 1,
                color: Color(0x1AFFFFFF),
              ),
            ),
            _toCommonWidget("分享", "icon_share_poster", _share),
          ]),
        ),
        Container(
            color: Color(0xFF21263C),
          height: bottomH,
          padding: EdgeInsets.only(bottom: bottomH),
        ),
      ],
    );
  }

  ///通用底部item
  Widget _toCommonWidget(String name, String icon, VoidCallback callback) {
    return Expanded(
      child: Container(
        height: 50,
        child: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            callback.call();
          },
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                "images/${icon}.png",
                height: 22,
                width: 22,
              ),
              SizedBox(
                width: 4,
              ),
              Text(
                name,
                style: TextStyle(
                    fontSize: 13,
                    color: ThemeRepository.getInstance()
                        .getTextMainColor_D0E0F7()),
              )
            ],
          ),
        ),
      ),
    );
  }

  _download() {
    _downloadOrShare = "00";
    loading(true, msg: "下载中");
    _webViewController?.evaluateJavascript('download_img()');
  }

  _edit() {
    String url = _loadUrl + "&is_edit=01";
    EditPosterPage.navigatorPush(context, url, widget?.id, widget?.hsn, widget?.intoflg);
  }

  _share() {
    SharePosterMenuDialog.navigatorPushDialog(context, () {
      _downloadOrShare = "01";
      _shareFlag = "00";
      loading(true, msg: "加载中");
      _webViewController?.evaluateJavascript('download_img()');
      RouterUtils.pop(context);
    }, () {
      _downloadOrShare = "01";
      _shareFlag = "01";
      loading(true, msg: "加载中");
      _webViewController?.evaluateJavascript('download_img()');
      RouterUtils.pop(context);
    });
  }

  _bigImage() {
    _downloadOrShare = "02";
    loading(true, msg: "加载中");
    _webViewController?.evaluateJavascript('download_img()');
  }

  ///切换logo显示js type 01显示  02隐藏
  _toggleLogo(String type) {
    //logoflg 00显示 01不显示

    _webViewController?.evaluateJavascript('logo_show_hide(${type})');
    _viewModel.updateLogo(context, widget?.id, (widget?.showSelectAddress ?? false) ? "02" : "01", ("01" == type)?"00":"01");

  }


  ///切换地址显示js type 01显示  02隐藏
  _toggleAddress(String type) {
    _webViewController?.evaluateJavascript('address_show_hide(${type})');
    _viewModel.updateAddress(context, widget?.id, (widget?.showSelectAddress ?? false) ? "02" : "01", ("01" == type)?"00":"01");
  }

  JavascriptChannel _logoJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'uploadComplete',
        onMessageReceived: (JavascriptMessage message) {
          print("收到了js回调");
          print(message.message);
          loading(false);
          // ToastUtils.toast(msg: "已生成", context: context);
        });
  }

  JavascriptChannel _addressJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'uploadComplete',
        onMessageReceived: (JavascriptMessage message) {
          print("收到了js回调");
          print(message.message);
          loading(false);
          // ToastUtils.toast(msg: "已生成", context: context);
        });
  }


  JavascriptChannel _alertJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'uploadComplete',
        onMessageReceived: (JavascriptMessage message) {
          print("收到了js回调");
          print(message.message);
          loading(false);
          setState(() {
            isUrlLoadComplete = true;
          });
          // ToastUtils.toast(msg: "已生成", context: context);
        });
  }

  JavascriptChannel _clickJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'clickPoster',
        onMessageReceived: (JavascriptMessage message) {
          if(showBubble){
            setState(() {
              showBubble = false;
            });
            return;
          }
          print("收到了点击回调");
          _bigImage();
        });
  }

  JavascriptChannel _downloadJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'downloadPoster',
        onMessageReceived: (JavascriptMessage message) async {
          print("下载图片收到了js回调");
          print(message.message);
          if (message != null &&
              StringUtils.isNotEmpty(message.message) &&
              message.message.contains(",")) {
            String base64Str = message.message.split(",")[1];
            if ("00" == _downloadOrShare) {
              //下载
              Future<String> imageResult = SaveUtils.saveImage(base64Url: base64Str);
              imageResult.then((saveResult) {
                if (StringUtils.isNotEmpty(saveResult)) {
                  loading(false);
                  toast(saveResult);
                }
              });

              _viewModel.downloadSharePoster(widget?.hsn, widget?.id,
                  (widget?.showSelectAddress ?? false) ? "02" : "01", "01", "");
            } else if ("01" == _downloadOrShare) {
              //分享
              // _weChatShare(context, message.message);
              String imagePath =
              await FileUtils.createFileFromString(base64Str);
              if (StringUtils.isNotEmpty(imagePath)) {
                loading(false);
                _weChatShare(context, imagePath, _shareFlag);
              }
              _viewModel.downloadSharePoster(
                  widget?.hsn,
                  widget?.id,
                  (widget?.showSelectAddress ?? false) ? "02" : "01",
                  "02",
                  "微信");
            } else if ("02" == _downloadOrShare) {
              //查看大图
              String imagePath =
              await FileUtils.createFileFromString(base64Str);
              if (StringUtils.isNotEmpty(imagePath)) {
                loading(false);
                VgPhotoPreview.single(context, imagePath,
                    loadingImageQualityType: ImageQualityType.middleDown);
              }
            }
          } else {
            toast("下载失败，请重试");
            loading(false);
          }
        });
  }

  String getUrl(String posterUrl, CompanyAndAddressBean companyAndAddressBean,
      {String currentAddress}) {
    String name = "";
    String address = "";
    String logo = "";
    bool transFlag = false;
    if(StringUtils.isNotEmpty(currentAddress)){
      name = currentAddress;
    }else{
      if(StringUtils.isNotEmpty(widget?.gps??"")){
        //有gps，使用地址列表第一个构建address跟name
        if (StringUtils.isNotEmpty(
            companyAndAddressBean.addressList[0].branchname)) {
          name = companyAndAddressBean.addressList[0].branchname;
        }
        if (StringUtils.isNotEmpty(
            companyAndAddressBean.addressList[0].cbid) && StringUtils.isEmpty(_cbid)) {
          _cbid = companyAndAddressBean.addressList[0].cbid;
        }
        if (StringUtils.isNotEmpty(
            companyAndAddressBean.addressList[0].address)) {
          address = companyAndAddressBean.addressList[0].address;
          if(StringUtils.isEmpty(_selectAddress)){
            _selectAddress = address;
          }
        }
      }else{
        if (!StringUtils.isEmpty(
            companyAndAddressBean?.comCompany?.companynick ?? "")) {
          name = companyAndAddressBean?.comCompany?.companynick ?? "";
        } else {
          name = companyAndAddressBean?.comCompany?.companyname ?? "";
        }
      }
    }
    if (companyAndAddressBean?.addressList != null &&
        companyAndAddressBean.addressList.length > 0) {
      companyAndAddressBean.addressList.forEach((element) {
        if(StringUtils.isNotEmpty(_cbid) && (_cbid??"") == element?.cbid){
          address = element.address;
        }
      });
    }else if (StringUtils.isNotEmpty(companyAndAddressBean?.loginAddress)) {
      address = companyAndAddressBean?.loginAddress;
    } else if (!StringUtils.isEmpty(
        companyAndAddressBean?.comCompany?.address ?? "")) {
      address = companyAndAddressBean?.comCompany?.address ?? "";
    }


    // if (StringUtils.isNotEmpty(currentAddress)) {
    //   address = currentAddress;
    // } else {
    //   if (StringUtils.isNotEmpty(companyAndAddressBean?.loginAddress)) {
    //     address = companyAndAddressBean?.loginAddress;
    //   } else if (!StringUtils.isEmpty(
    //       companyAndAddressBean?.comCompany?.address ?? "")) {
    //     address = companyAndAddressBean?.comCompany?.address ?? "";
    //   } else {
    //     if (companyAndAddressBean?.addressList != null &&
    //         companyAndAddressBean.addressList.length > 0) {
    //       if (StringUtils.isNotEmpty(companyAndAddressBean.addressList[0].address)) {
    //         address = companyAndAddressBean.addressList[0].address;
    //       }
    //     }
    //   }
    // }
    ComLogoBean logoBean = UserRepository.getInstance().userData.comLogo;
    if(logoBean != null){
      if(StringUtils.isNotEmpty(logoBean.squareTransparentLogo) && "-1" != logoBean.squareTransparentLogo){
        logo = logoBean.squareTransparentLogo;
        transFlag = true;
      }else if(StringUtils.isNotEmpty(logoBean.squareOpaqueLogo) && "-1" != logoBean.squareOpaqueLogo){
        logo = logoBean.squareOpaqueLogo;
      }else{
        if (!StringUtils.isEmpty(
            companyAndAddressBean?.comCompany?.companylogo ?? "")) {
          logo = companyAndAddressBean?.comCompany?.companylogo ?? "";
        }
      }
    }else{
      if (!StringUtils.isEmpty(
          companyAndAddressBean?.comCompany?.companylogo ?? "")) {
        logo = companyAndAddressBean?.comCompany?.companylogo ?? "";
      }
    }

    String url;
    if (StringUtils.isNotEmpty(logo)) {
      url =
      "$posterUrl?downloadflg=01&ai_reception=01&name=${Uri.encodeComponent(name)}&address=${Uri.encodeComponent(address)}&logo=${Uri.encodeComponent(logo)}";
      // url = "http://etpic.we17.com/test/20210617140614_1605.html?downloadflg=01&name=${name}&address=${address}&logo=${logo}";
    } else {
      url =
      "$posterUrl?downloadflg=01&ai_reception=01&name=${Uri.encodeComponent(name)}&address=${Uri.encodeComponent(address)}";
      // url = "http://etpic.we17.com/test/20210617140614_1605.html?downloadflg=01&name=${name}&address=${address}";
    }
    if(!_showLogo){
      url = url + "&logohide=01";
    }
    if(!_showAddress || !_posterSplicing){
      url = url + "&addresshide=01";
    }
    if(transFlag){
      url = url + "&transparent=01";
    }
    if(StringUtils.isNotEmpty(widget?.addressdiy??"")){
      // url = url + "&addressdiy=${widget?.addressdiy??""}";
      url = url + "&addressdiy=${Platform.isIOS ? Uri.encodeComponent(widget?.addressdiy??"") : (widget?.addressdiy??"")}";
    }
    if(StringUtils.isNotEmpty(widget?.namediy??"")){
      // url = url + "&namediy=${widget?.namediy??""}";
      url = url + "&namediy=${Platform.isIOS ? Uri.encodeComponent(widget?.namediy??"") : (widget?.namediy??"")}";
    }
    if(StringUtils.isNotEmpty(widget?.logodiy??"")){
      // url = url + "&logodiy=${widget?.logodiy??""}";
      url = url + "&logodiy=${Platform.isIOS ? Uri.encodeComponent(widget?.logodiy??"") : (widget?.logodiy??"")}";
    }
    if(StringUtils.isNotEmpty(widget?.splpicurl??"")){
      // url = url + "&splpicurl=${widget?.splpicurl??""}";
      url = url + "&splpicurl=${Platform.isIOS ? Uri.encodeComponent(widget?.splpicurl??"") : (widget?.splpicurl??"")}";
    }
    url += "&today=${Uri.encodeComponent(LunarCalendar(DateTime.now()).getValue())}";
    print("生成的url");
    print(url);
    return url;
  }

  void _weChatShare(BuildContext context, String filePath, String shareFlag) {
    print("filePath:" + filePath);
    SSDKMap params = SSDKMap()
      ..setGeneral("AI前台App", "海报", [filePath], "", filePath, "", "", "", "",
          filePath, SSDKContentTypes.image);
    ShareRepository.getInstance().shareImageToWechat(context, params,
        platforms: ("00" == shareFlag)
            ? ShareSDKPlatforms.wechatTimeline
            : ShareSDKPlatforms.wechatSession);
  }
}
